#include "EditorSplitableLayoutModel.h"



void REditorSplitableLayoutModel::SetLayoutTree(REditorSplitableLayoutNodePtr InLayoutTree)
{
#ifdef DEBUG
    //检查树的合法性
    {
        //遍历树节点
        assert(!InLayoutTree->Parent && "根节点不应当有父节点");

        TVector<REditorSplitableLayoutNodePtr> Queue;
        Queue.Add(InLayoutTree);
        while(!Queue.Empty())
        {
            auto Node = Queue[0];
            Queue.RemoveAt(0);
            if(Node->IsA<REditorContainerSplitableLayoutNode>())
            {
                TSharedObjectPtr<REditorContainerSplitableLayoutNode>
                    ContainerNode=Node;

                assert(ContainerNode->ChildrenSize.Num()==ContainerNode->Children.Num());
                if(ContainerNode->ChildrenSize.Num()<2)
                {
                    assert(false&& "容器节点至少两个子节点");
                }

                for(auto Child: ContainerNode->Children)
                {
                    Queue.Add(Child);
                    assert(Child->Parent==ContainerNode&& "子节点的父节点设置错误");
                }

            }
            // else
            // {
            //     TSharedObjectPtr<REditorSplitableLayoutLeafNode>
            //         Leaf=Node;
                
            //     assert(Leaf->ItemWidgetModel&& "叶子节点缺少model");
            // }
        }
    }
#endif

    //清空旧的布局树
    Nodes.Clear();


    //层序遍历布局树
    TVector<REditorSplitableLayoutNodePtr> Queue;
    Queue.Add(InLayoutTree);

    while (!Queue.Empty())
    {
        auto Node = Queue[0];
        Queue.RemoveAt(0);

        Nodes.Add(Node);

        if(Node->IsA<REditorContainerSplitableLayoutNode>())
        {
            REditorContainerSplitableLayoutNodePtr ContainerNode = Node;
            Queue.Append(ContainerNode->Children);
        }
    }

    //计算每个节点的子节点索引
    SubNodeIndices.Resize(Nodes.Num());
    for (int64_t i = 0; i < Nodes.Num(); ++i)
    {
        auto Node = Nodes[i];
        if (Node->IsA<REditorContainerSplitableLayoutNode>())
        {
            REditorContainerSplitableLayoutNodePtr ContainerNode = Node;
            SubNodeIndices[i].Resize(ContainerNode->Children.Num());

            auto FirstChildIndex = Nodes.Find(ContainerNode->Children[0]).GetValue();
            for (int64_t j = 0; j < ContainerNode->Children.Num(); ++j)
            {
                SubNodeIndices[i][j]=FirstChildIndex + j;
            }
        }
    }

    OnLayoutChanged.ExecuteIfBound();
}

REditorSplitableLayoutNodePtr REditorSplitableLayoutModel::GetLayoutRoot()
{
    if(!Nodes.Empty())
    {
        return Nodes[0];
    }
    return nullptr;
}

void REditorSplitableLayoutModel::Clear()
{
    if(!Nodes.Empty())
    {
        Nodes.Clear();
        SubNodeIndices.Clear();
        OnLayoutChanged.ExecuteIfBound();
    }
}
